<template>
  <div class="cmt-container">
    <h3>发表评论</h3>
    <hr />
    <textarea placeholder="请输入要评论的内容(120字)" maxlength="120" v-model="msg"></textarea>
    <mt-button type="primary" size="large" plain @click="postComment">发表评论</mt-button>
    <div class="cmt-list">
      <div class="cmt-item" v-for=" (item,i) in comments" v-bind:key="item.id">
        <div
          class="cmt-title"
        >第{{ i+1 }}楼&nbsp;&nbsp;用户：{{item.user_name}} &nbsp;&nbsp;发表时间：{{item.add_time | dateFormat}}</div>
        <div class="cmt-content">{{ item.content === 'undefind' ? '此用户很懒什么都没说' : item.content}}</div>
      </div>
    </div>

    <mt-button type="danger" size="large" plain @click="getMore">加载更多</mt-button>
  </div>
</template>

<script>
import { Toast } from "mint-ui";
export default {
  data() {
    return {
      pageindex: 1, //默认展示第一页
      comments: [], //所有评论数据
      msg: "",
    };
  },
  created() {
    this.getCommentInfo();
  },
  methods: {
    getCommentInfo() {
      this.$http
        .get(
          "http://api.cms.liulongbin.top/api/getcomments/" +
            this.id +
            "?pageindex=" +
            this.pageindex
        )
        .then((res) => {
          if (res.data.status === 0) {
            // this.comments = res.data.message;
            // 每当点击加载更多按钮时 ，不要把老数据覆盖，而是进行拼接处理再一起渲染到页面中
            this.comments = this.comments.concat(res.data.message);
          } else {
            Toast("加载新闻信息失败");
          }
        });
    },
    getMore() {
      this.pageindex++;
      this.getCommentInfo();
    },
    postComment() {
      //检验是否为空的内容
      if (this.msg.trim().length === 0) {
        return Toast("评论内容为空");
      }
      //发表评论 axios post请求
      //参数1：请求的URL地址
      // 参数2：提交给服务器的数据对象 {content：this.msmg}
      this.$http
        .post("http://api.cms.liulongbin.top/api/postcomment/" + this.id, {
          content: this.msg.trim(),
        })
        .then((res) => {
          if (res.data.status === 0) {
            // 1.拼接出一个评论对象
            var cmt = {
              user_name: "匿名用户",
              add_time: Date.now(),
              content: this.msg.trim(),
            };
            this.comments.unshift(cmt);
            this.msg = '';
         
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
  },
  props: ["id"],
};
</script>

<style lang="scss" scoped>
.cmt-container {
  h3 {
    font-size: 18px;
  }
  textarea {
    font-size: 14px;
    height: 100px;
    margin-bottom: 5px;
  }
  .cmt-list {
    margin-top: 10px;
    .cmt-title {
      font-size: 13px;
      height: 30px;
      line-height: 30px;
      background-color: #d3d3d3;
    }
    .cmt-content {
      font-size: 15px;
      text-indent: 2em;
      line-height: 30px;
    }
  }
}
</style>